package com.yand.serviceimpl.business.classtime;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yand.api.entity.business.classtime.THfClassLog;
import com.yand.api.entity.business.classtime.THfScheduleClass;
import com.yand.api.entity.business.custom.THfStudent;
import com.yand.api.entity.business.order.THfOrder;
import com.yand.api.entity.common.Result;
import com.yand.api.service.business.classtime.ClassLogService;
import com.yand.api.service.business.classtime.ScheduleClassService;
import com.yand.api.service.business.custom.StudentService;
import com.yand.api.service.business.order.OrderService;
import com.yand.api.util.DateUtils;
import com.yand.mapper.business.classtime.THfScheduleClassMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 *
 */
@Service
public class ScheduleClassServiceImpl implements ScheduleClassService {

    @Autowired
    private THfScheduleClassMapper scheduleClassMapper;

    @Autowired
    private StudentService studentService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ClassLogService classLogService;

    @Override
    public PageInfo<THfScheduleClass> queryAllStudentList(THfScheduleClass scheduleClass) {
        PageHelper.startPage(scheduleClass.getPageNum(), scheduleClass.getPageSize());

        return PageInfo.of(scheduleClassMapper.selectAllScheduleClassList(scheduleClass));
    }

    /**
     * 添加排课日程信息
     * @param scheduleClass
     */
    @Override
    public void insertScheduleClass(THfScheduleClass scheduleClass) {
       String studentIds = scheduleClass.getStudentIds();
       String [] studentIdArray = studentIds.split(",");

       for(int i = 0 ; i < studentIdArray.length; i ++){
           //获取学生id
           String studentId =studentIdArray[i];

           THfOrder order = orderService.getOrderByStudentId(Integer.parseInt(studentId));
           scheduleClass.setStudentId(Integer.parseInt(studentId));
           scheduleClass.setOderId(order.getOrderId());
           String endLimitTime = scheduleClass.getLimitTime().split("-")[1];
           Date beginDate = scheduleClass.getBeginClassDate();
           String beginDateStr = DateUtils.parseDate(beginDate,"yyyy-MM-dd");
           scheduleClass.setExtand1(beginDateStr+" "+endLimitTime);
           //添加课时数
           scheduleClass.setExtand2(scheduleClass.getExtand2());
           scheduleClassMapper.insertSelective(scheduleClass);
       }


    }

    @Override
    public void deleteClass(String date, String tileLimit, String tearcherId) {
        THfScheduleClass scheduleClass = new THfScheduleClass();
        Date utilDate = DateUtils.formatDateStr(date,"yyyy-MM-dd");
        scheduleClass.setBeginClassDate(utilDate);
        scheduleClass.setTeacherId(Integer.parseInt(tearcherId));
        scheduleClass.setLimitTime(tileLimit);
        scheduleClassMapper.deleteScheduleClass(scheduleClass);
    }

    /**
     *  判断是否合理性
     * @param studentIds
     * @param date
     * @param timeLimit
     * @return
     */
    @Override
    public Result checkClassPlan(String studentIds, String date, String timeLimit) {
        String [] studentArray = studentIds.split(",");
        THfScheduleClass scheduleClass = null;
        Result result = new Result(0);
        for(int i =0 ; i < studentArray.length; i ++){
            scheduleClass = new THfScheduleClass();
            String studentId = studentArray[i];
            scheduleClass.setStudentId(Integer.parseInt(studentId));
            Date utilDate = DateUtils.formatDateStr(date,"yyyy-MM-dd");
            scheduleClass.setBeginClassDate(utilDate);
            List<THfScheduleClass> scheduleClassList = scheduleClassMapper.selectAllScheduleClassList(scheduleClass);
            if(scheduleClassList.size() > 0){
                boolean flag = true;
                THfScheduleClass scheduleClassOld = null;
                for(int j = 0 ; j < scheduleClassList.size() ; j ++){
                    scheduleClassOld = scheduleClassList.get(0);
                    if(!checkLimit(scheduleClassOld,date,timeLimit)){
                        THfStudent student = studentService.getStudentBean(Long.valueOf(studentId));
                        result.setCode(1);
                        result.setMessage("学生: "+student.getStudentName()+"时间段:"+scheduleClassOld.getLimitTime()+", 已安排其他上课,与时间段"+timeLimit+"冲突,请重新排课");
                        flag = false;
                        break;
                    }
                }

                if(!flag){
                    break;
                }

            }
        }

        return result;
    }


    /**
     * 上课信息确认
     *  1， 更改 排课计划表的状态由0改为1
     *  2， 对订单表进行增加减少金额操作
     *  3， 添加到上课计划表中
     * @param id
     * @return
     */
    @Override
    public Result sureAttendClass(String id) {
        THfScheduleClass scheduleClass = scheduleClassMapper.selectByPrimaryKey(Integer.parseInt(id));
        scheduleClass.setStatus(1);
        scheduleClassMapper.updateByPrimaryKeySelective(scheduleClass);

        String orderId = scheduleClass.getOderId();
        THfOrder order = orderService.getOrderById(Integer.parseInt(orderId));
        //课时单价
        String price = order.getExtand2();
        BigDecimal discount = order.getDiscount();
        BigDecimal surplusMoney = order.getSurplusMoney();
        Integer surplusClassNum = order.getSurplusClassnum();
        //课时数
        String classNum = scheduleClass.getExtand2();

        BigDecimal actualPrice =new BigDecimal(price).multiply(discount);

        BigDecimal actualPrices =actualPrice.multiply(new BigDecimal(classNum));

        surplusMoney = surplusMoney.subtract(actualPrices);
        surplusClassNum = surplusClassNum - Integer.parseInt(classNum);

        order.setSurplusClassnum(surplusClassNum);
        order.setSurplusMoney(surplusMoney);

        orderService.updateOrder(order);


        THfClassLog classLog = new THfClassLog();
        classLog.setStudentId(scheduleClass.getStudentId());
        classLog.setOrderId(classLog.getOrderId());
        classLog.setScheduleId(scheduleClass.getId());
        classLog.setClassNum(classNum);
        classLog.setCostMoney(new BigDecimal(price).multiply(new BigDecimal(classNum)));
        classLog.setDiscount(discount);
        classLog.setActualMoney(actualPrices);
        classLog.setOrderType(0);
        classLogService.insertClassLog(classLog);
        return new Result(0);
    }


    /**
     * 判断是否在
     * @param scheduleClassOld
     * @param targetDate
     * @param targetTimelimit
     * @return
     */
    private boolean checkLimit(THfScheduleClass scheduleClassOld, String targetDate, String targetTimelimit){
        Date date = scheduleClassOld.getBeginClassDate();
        String dateStr = DateUtils.parseDate(date,"yyyy-MM-dd");
        String limitTime = scheduleClassOld.getLimitTime();
        String [] limitTimeArray = limitTime.split("-");
        String beginDateTimeStr = dateStr + limitTimeArray[0];
        Date beginDateTime = DateUtils.formatDateStr(beginDateTimeStr,"yyyy-MM-dd HH:mm:ss");
        String endDateTimeStr = dateStr + limitTimeArray[1];
        Date endDateTime = DateUtils.formatDateStr(endDateTimeStr,"yyyy-MM-dd HH:mm:ss");
        String [] targetLimitTimeArray = targetTimelimit.split("-");
        String targetBeginDateTimeStr = targetDate + targetLimitTimeArray[0];
        Date targetBeginDate = DateUtils.formatDateStr(targetBeginDateTimeStr,"yyyy-MM-dd HH:mm:ss");
        String targetEndDateTimeStr = targetDate + targetLimitTimeArray[1];
        Date targetEndDateTime = DateUtils.formatDateStr(targetEndDateTimeStr,"yyyy-MM-dd HH:mm:ss");

        if(targetBeginDate.before(beginDateTime) && targetEndDateTime.before(beginDateTime)){
             return true;
        }else if(targetEndDateTime.after(endDateTime) && targetBeginDate.after(endDateTime)){
             return true;
        }else{
            return false;
        }

    }





}
